﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataAccessLayer.Helper
{
    public class EntityKeyGenerator
    {
        public static readonly string connectionString = string.Format(System.Configuration.ConfigurationManager.ConnectionStrings["ADO.NET"].ConnectionString, Common.Helpers.GlobalVariables.Instance.dbConnection);

        private static EntityKeyGenerator m_Instance;

        public static EntityKeyGenerator Instance
        {
            get
            {
                if (m_Instance == null)
                    m_Instance = new EntityKeyGenerator();

                return m_Instance;
            }
        }

        public long GenerateEntityKey(string schema, string tableName)
        {
            long entityKey = 0;
            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    using (SqlCommand comm = new SqlCommand("dbo.sp_GetEntityKey", conn))
                    {
                        if (conn.State != ConnectionState.Open)
                            conn.Open();

                        SqlTransaction sqlTran = conn.BeginTransaction();

                        comm.Transaction = sqlTran;
                        comm.CommandType = System.Data.CommandType.StoredProcedure;
                        comm.Parameters.Add(new SqlParameter("@Schema", schema));
                        comm.Parameters.Add(new SqlParameter("@TableName", tableName));
                        DataTable dt = new DataTable();
                        SqlDataAdapter sda = new SqlDataAdapter();

                        foreach (SqlParameter param in comm.Parameters)
                        {
                            param.Direction = ParameterDirection.Input;
                            param.DbType = DbType.String;
                        }

                        sda.SelectCommand = comm;
                        sda.Fill(dt);


                        if (dt != null && dt.Rows != null && dt.Rows.Count > 0)
                            entityKey = dt.Rows[0].Field<long>("Id");

                    }
                    if (conn.State == ConnectionState.Open)
                        conn.Close();
                }
                return entityKey;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

    }
}
